<?php

class Model_Role
{
    var $sys;
    private $table_name = "M_ROLE";
    
    public function __construct()
    {
        $this->sys = new Model_SiteManage();
    }
    //
    public function insert($data)
    {
        $db = new Model_DB();
        return $db->insert($this->table_name, $data);
    }
    public function update($id, $data)
    {
        $db = new Model_DB();
        return $db->update($id, $this->table_name, $data);
    }
    public function get($id)
    {
        $db = new Model_DB();
        $sql = sprintf("select * from ".$this->table_name." where id = " . $db->escape($id) . " and enabled = 1");
        $db->query($sql);
        return $db->fetch();
    }
    public function getListCount($data)
    {
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        $sql   = "select count(*) from ".$this->table_name;
        $sql  .= (!empty($where) ? " where ".implode(' AND ', $where) : "");
        $db->query($sql);
        if ($db->res){
            return array_shift($res = $db->fetch());
        }
        return false;
    }
    public function getList($data, $orderby = 'id asc', $limit = '', $offset = '')
    {//var_dump($data);exit;
        $list  = array();
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        //$sql   = "select * from ".$this->table_name." left join D_STAFF_AUTH ON ".$this->table_name.".id = D_STAFF_AUTH.staff_id";
        $sql   = "select * from ".$this->table_name." ";
        $sql  .= (!empty($where) ? " where ".implode(' AND ', $where) : "") . (!empty($orderby) ? " order by {$orderby}" : "") . (!empty($limit) ? " limit {$limit}" : "") . (!empty($offset) ? " offset {$offset}" : "");
        
        //echo $sql;exit;
        
        $db->query($sql);
        if ($db->res){
            while($res = $db->fetch()){
                if(isset($res['id'])){
                    $list[$res['id']] = $res;
                }
                else{
                    $list[] = $res;
                }
            }
        }
        return $list;
    }

    private function createSearchCondition($data, $prefix = '')
    {
        $db    = new Model_DB();
        $where = array();
        if ($prefix != ''){
            $prefix = $prefix . '.';
        }
        $where[] = "{$prefix}enabled = 1";
        //$where[] = "{$prefix}site_id = ". $this->sys->getCurrentSiteID();//不要？

        foreach($db->getFieldList($this->table_name) as $key => $_){
            
            //if (isset($data[$key]) && !empty($data[$key])){//emptyは文字列の0でもtrueとなるので注意
            if (isset($data[$key]) && $data[$key] != ''){
                $value = $db->escape($data[$key]);
                if ($key == 'name'){
                    $where[] = "{$prefix}{$key} collate utf8_unicode_ci like '%{$value}%'";
                }else{
                    $where[] = "{$prefix}{$key} = '{$value}'";
                }
            }
        }

        foreach($db->getFieldList('D_STAFF_AUTH') as $key => $_){
            if (isset($data[$key]) && !empty($data[$key])){
                $value = $db->escape($data[$key]);
                $where[] = "{$prefix}{$key} = '{$value}'";
            }
        }
        return $where;
    }
    
    public function validate(&$data, &$err)
    {
        $validate = new Model_Validate();
        // required
        $keys = explode(',', 'site_id,name,actived');
        foreach($keys as $key){
            if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                $err[$key] = $validate->getMessages("NotEmpty");
            }
        }
        
        // ロール名 重複チェック
        if($data['id'] == ''){
            $count = $this->getListCount(array("site_id"=>$data["site_id"], "name"=>$data['name']));
        }else{
            //getListCountはwhereで!=が使えないので、ここはsqlを書いている
            //$count = $this->getListCount();
            $db = new Model_DB();
            $sql = sprintf( "SELECT id FROM M_ROLE WHERE enabled = 1 AND site_id = '%s' AND name = '%s' AND id != '%u'",
                            $db->escape($data['site_id']),
                            $db->escape($data['name']),
                            $db->escape($data['id'])
                    );
            $db->query($sql);
            $count = $db->num_rows();
        }
        if( $count > 0 ){
            $err['name'] = $validate->getMessages("Duplicate");
        }

        return empty($err);
    }
    
    //
    public function getFormKeys()
    {
        $db = new Model_DB();
        return array_keys($db->getFieldList($this->table_name));
    }
    //　状態
    public function getStatusMap()
    {
        $map    = array();
        $map[0] = '非公開';
        $map[1] = '公開';
        $map[2] = '仮登録';
        return $map;
    }
    public function getStatusName($id)
    {
        $map = $this->getStatusMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
}
?>